# IESpecific automatically parses all css and js files inside
# #{RAILS_ROOT}/public/stylesheets/ie-specific and 
# #{RAILS_ROOT}/public/javascripts/ie-specific , and then includes them in conditional 
# tags (generated from the filenames) to only show certain stylesheets to certain versions of Internet Explorer
#
# Author::     Tom Armitage  (mailto:tom@infovore.org)
# Copyright::  Copyright (c) 2006 T. Armitage
# License::    Distributes under the same terms as Rails

module IESpecific
  
  # Display  an appropriately formatted list of stylesheets and javascripts to the template.
  def ie_specific_styles_and_scripts
     begin
       dirname = "ie_specific"

       hacks = {}
       # hacks => {:ie-5 => {css}, :lte-ie-6 => {:css, :js}}

       css_dir = "#{RAILS_ROOT}/public/stylesheets/#{dirname}" 
       js_dir = "#{RAILS_ROOT}/public/javascripts/#{dirname}"

       if FileTest.exist? css_dir and FileTest.directory? css_dir
          Dir.entries(css_dir).each do |f|
             if f.split(".").last == "css"
                name = File.basename(f, ".css")
                hacks[name.intern] ? hacks[name.intern] << :css : hacks[name.intern] = [:css]
             end
          end
       end

       if FileTest.exist? js_dir and FileTest.directory? js_dir
          Dir.entries(js_dir).each do |f|
             if f.split(".").last == "js"
                name = File.basename(f, ".js")
                hacks[name.intern] ? hacks[name.intern] << :js : hacks[name.intern] = [:js]
             end
          end
       end

       output = ""

       hacks.each do |condition, types| 
          output << "<!--[if #{condition.to_s.gsub("-", " ")}]>\n"
          if types.include? :css
             output <<  "\t<style type='text/css' media='screen, projection'>\n"
             output <<  "\t\t@import '/stylesheets/#{dirname}/#{condition}.css';\n"
             output <<  "\t</style>\n"
          end
          if types.include? :js
             output << "\t<script type='text/javascript' src='/javascripts/#{dirname}/#{condition}.js'></script>\n"
          end
          output << "<![endif]-->\n\n"
       end
       output
    rescue
      ""
    end
  end
end